//
//  LoginViewController.m
//  LBBaseOC
//
//  Created by Gary on 15/7/4.
//  Copyright (c) 2015年 Lebo. All rights reserved.
//

#import "LoginViewController.h"
#import "BaseTableViewController.h"
#import "Common.h"
#import "DTCoreText.h"

static const NSInteger kAlertTagVersionUpdateFail = 1000;

@interface LoginViewController () <UIAlertViewDelegate, UITextFieldDelegate, DTAttributedTextContentViewDelegate> {
    
}

@property (weak, nonatomic) IBOutlet UITextField *accountTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (nonatomic, retain) NSString *appItunesUrl;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view
    [Common setRootViewController:self];
    
    _accountTextField.text = [Common currentUserInfo][kAPIParamUserName];
    _accountTextField.delegate = self;
    _passwordTextField.delegate = self;
    
#ifndef RUN_IN_PRODUCTION_ENV
    UISwipeGestureRecognizer *gr = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                             action:@selector(handleViewSwipe:)];
    gr.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:gr];
    self.view.userInteractionEnabled = YES;
#endif
    
    [self performSelector:@selector(getBrand) withObject:nil afterDelay:kPerformDelay];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 视图初始化

#pragma mark - 业务处理

- (BOOL)checkRequestData {
    if ([Common isEmptyString:self.accountTextField.text]) {
        [Common showLocalMessage:@"AccountIsEmpty"];
        return NO;
    }
    
    if ([Common isEmptyString:self.passwordTextField.text]) {
        [Common showLocalMessage:@"PasswordIsEmpty"];
        return NO;
    }
    
    if (![Common isAccount:[Common trim:self.accountTextField.text]]) {
        [Common showLocalMessage:@"AccountIsNotValid"];
        return NO;
    }
    
    if (![Common isPassword:[Common trim:self.passwordTextField.text]]) {
        [Common showLocalMessage:@"PasswordIsNotValid"];
        return NO;
    }
    
    return YES;
}

- (void)getBrand {
    //[BF callBusinessFunc:BusinesID(ECarManager, ECarGetBrandList) inParam:nil];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dispatch_async(dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT), ^{
            // 处理耗时操作的代码块...
            //[NSThread sleepForTimeInterval:10.f];
            [BF callBusinessFunc:BusinesID(ECarManager, ECarGetBrandList) inParam:nil];
            //通知主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新，
            });
        });
    });
}

- (void)checkVersion {
    [BF callBusinessFunc:BusinesID(ELoginManager, ELoginVersionUpdate) inParam:[self makeRequestParams:[self requestDic:nil] requestInfo:nil]];
}

- (void)login {
    NSMutableDictionary *requestDic = [self requestDic:@{kAPIParamUserName : [Common trim:self.accountTextField.text],
                                                         kAPIParamPassword : [Common trim:self.passwordTextField.text]}];
    NSDictionary *dic = [self makeRequestParams:requestDic requestInfo:nil];
    [BF callBusinessFunc:BusinesID(ELoginManager, ELoginLogin) inParam:dic];
}

#pragma mark - 事件响应

- (IBAction)clickLoginBtn:(id)sender {
    [_baseComponent hideKeyboard];
    
    /* For Debug
     UIViewController *vc = [Common viewController:@"FilterViewController"];
     [self.navigationController pushViewController:vc animated:YES];
     return;
     */

    if ([self checkRequestData]) {
        [_baseComponent showMask];
        [self checkVersion];
    }
}

- (void)servicePhoneLinkPushed:(id)sender {
    [Common callServicePhone];
}

- (void)handleViewSwipe:(UISwipeGestureRecognizer*)gr {
    if (_baseComponent.editingTextInputView) {
        [_baseComponent.editingTextInputView resignFirstResponder];
    }
    if(gr.direction==UISwipeGestureRecognizerDirectionLeft) {
        [self performSegueWithIdentifier:@"loginPushServerConfigSegue" sender:self];
    }
}

#pragma mark - 框架函数

- (void)onBusinessNotify:(NSUInteger)notifyID inParam:(id)inParam {
    HandleNetworkError;
    switch (notifyID) {
        case BusinesID(ELoginManager, ELoginVersionUpdateSucc): {
            //版本检测成功
            LogDebug(@"Version succ");
            //版本检测成功后继续执行登录请求
            [self login];
            break;
        }
            
        case BusinesID(ELoginManager, ELoginVersionUpdateFail): {
            //版本检测失败
            [_baseComponent hideMask];
            LogError(@"Version fail");
            NSDictionary *dic = [(NSDictionary*)inParam objectForKey:kNetworkResponseData];
            if (20100 == [[dic objectForKey:kNetworkResponseRetcodeKey] integerValue]) {
                self.appItunesUrl = [dic objectForKey:kNetworkResponseRetdataKey];
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:[Common getLocalStr:@"CommonTitlePrompt"]
                                                                 message:[Common getLocalStr:@"NewVersionIsFound"]
                                                                delegate:self
                                                       cancelButtonTitle:[Common getLocalStr:@"CommonTitleCancel"]
                                                       otherButtonTitles:[Common getLocalStr:@"CommonTitleConfirm"], nil];
                alert.tag = kAlertTagVersionUpdateFail;
                [alert show];
            } else {
                NSString *message = dic ? [dic objectForKey:kNetworkResponseMessageKey] : nil;
                [Common showAlert:[Common getLocalStr:@"CommonTitlePrompt"] message:message];
                LogError(@"message: %@", message);
            }
            break;
        }
            
        case BusinesID(ELoginManager, ELoginLoginSucc): {
            //登录成功
            [_baseComponent hideMask];
            LogInfo(@"Login success");;
            //跳转到主页
            UIViewController *vc = [Common viewController:@"HomeViewController"];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
            
        case BusinesID(ELoginManager, ELoginLoginFail): {
            //登录失败
            [_baseComponent hideMask];
            NSDictionary *dic = [(NSDictionary*)inParam objectForKey:kNetworkResponseData];
            NSString *message = dic ? [dic objectForKey:kNetworkResponseMessageKey] : nil;
            [Common showAlert:[Common getLocalStr:@"LoginFail"] message:message];
            LogError(@"login fail: %@", message);
            break;
        }
            
        default:
            break;
    }
}

- (BOOL)networkRequestFailed:(NSError*)error {
    [Common showToast:[error.userInfo objectForKey:kNetworkResponseErrorMessageKey]];
    return YES;
}


#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (kAlertTagVersionUpdateFail == alertView.tag) {
        if (1 == buttonIndex) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.appItunesUrl]];
        }
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _accountTextField) {
        [_passwordTextField becomeFirstResponder];
        [_baseComponent riseWindowHeight];
    } else if (textField == _passwordTextField) {
        [self clickLoginBtn:nil];
    }
    
    return YES;
}

#pragma mark - DTAttributedTextContentViewDelegate

- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttributedString:(NSAttributedString *)string frame:(CGRect)frame {
    NSDictionary *attributes = [string attributesAtIndex:0 effectiveRange:NULL];
    
    NSURL *URL = [attributes objectForKey:DTLinkAttribute];
    NSString *identifier = [attributes objectForKey:DTGUIDAttribute];
    
    
    DTLinkButton *button = [[DTLinkButton alloc] initWithFrame:frame];
    button.URL = URL;
    button.minimumHitSize = CGSizeMake(25, 25); // adjusts it's bounds so that button is always large enough
    button.GUID = identifier;
    
    // get image with normal link text
    UIImage *normalImage = [attributedTextContentView contentImageWithBounds:frame options:DTCoreTextLayoutFrameDrawingDefault];
    [button setImage:normalImage forState:UIControlStateNormal];
    
    // get image for highlighted link text
    UIImage *highlightImage = [attributedTextContentView contentImageWithBounds:frame options:DTCoreTextLayoutFrameDrawingDrawLinksHighlighted];
    [button setImage:highlightImage forState:UIControlStateHighlighted];
    
    // use normal push action for opening URL
    if ([string.string isEqualToString:kServicePhoneNumber]) {
        [button addTarget:self action:@selector(servicePhoneLinkPushed:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    // demonstrate combination with long press
    //UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(linkLongPressed:)];
    //[button addGestureRecognizer:longPress];
    
    return button;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
